<?php

/**
 * 管理后台 API 接口
 * 处理所有管理后台的业务逻辑请求
 */

session_start();

// 引入配置文件
$funAjaxPath = dirname(__DIR__) . '/fun.ajax.php';
if (file_exists($funAjaxPath)) {
    include_once $funAjaxPath;
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '系统配置文件未找到']);
    exit;
}

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('X-Powered-By: DaoHang Admin API');

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'exportVisitRecords') {
    // 导出功能允许GET请求
    $input = $_GET;
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取POST请求数据
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input === null) {
        // 如果不是JSON，尝试获取表单数据
        $input = $_POST;
    }
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => '只允许POST请求']);
    exit;
}

$action = $input['action'] ?? '';

/**
 * 保存配置到文件
 */
function saveConfig($filePath, $siteConf, $linkData)
{
    $phpCode = "<?php\n\n";
    $phpCode .= "\$conf = " . preg_replace(['/^array \(/', '/\)$/'], ['[', ']'], var_export($siteConf, true)) . ";\n\n";
    $dataExport = var_export($linkData, true);
    $dataExport = preg_replace('/^array \(/', '[', $dataExport);
    $dataExport = preg_replace('/\)$/', ']', $dataExport);
    $dataExport = preg_replace('/\s*\d+\s*=>\s*array\s*\(/', '[', $dataExport);
    $dataExport = preg_replace('/array\s*\(/', '[', $dataExport);
    $dataExport = preg_replace('/\)/', ']', $dataExport);
    $phpCode .= "\$Data = " . $dataExport . ";\n";
    return file_put_contents($filePath, $phpCode) !== false;
}

/**
 * 验证管理员权限
 */
function validateAdminAuth($action)
{
    global $conf;

    // 登录和设置密钥操作不需要验证
    if (in_array($action, ['login', 'setToken'])) {
        return true;
    }

    if (!isset($_SESSION['ADMINTOKEN']) || $_SESSION['ADMINTOKEN'] !== $conf['token']) {
        return false;
    }

    return true;
}

/**
 * 返回API响应
 */
function apiResponse($status, $message, $data = null)
{
    $response = [
        'status' => $status,
        'success' => ($status === 'success'),  // 兼容不同的前端调用
        'message' => $message,
        'timestamp' => time()
    ];

    if ($data !== null) {
        $response['data'] = $data;
    }

    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// 验证权限
if (!validateAdminAuth($action)) {
    apiResponse('error', '未授权访问，请重新登录');
}

// API路由处理
switch ($action) {
    case 'login':
        handleLogin($input);
        break;

    case 'setToken':
        handleSetToken($input);
        break;

    case 'logout':
        handleLogout();
        break;

    case 'updateSiteConfig':
        handleUpdateSiteConfig($input);
        break;

    case 'addLink':
        handleAddLink($input);
        break;

    case 'updateLink':
        handleUpdateLink($input);
        break;

    case 'deleteLink':
        handleDeleteLink($input);
        break;

    case 'reorderLinks':
        handleReorderLinks($input);
        break;

    case 'getLinksList':
        handleGetLinksList();
        break;

    case 'getSiteStats':
        handleGetSiteStats();
        break;

    case 'getVisitRecords':
        handleGetVisitRecords($input);
        break;

    case 'getVisitFiles':
        handleGetVisitFiles();
        break;

    case 'getOnlineVisitors':
        handleGetOnlineVisitors();
        break;

    case 'exportVisitRecords':
        handleExportVisitRecords($input);
        break;

    case 'recordVisit':
        handleRecordVisit($input);
        break;

    // case 'update_visit_duration':
    //     handleUpdateVisitDuration($input);
    //     break;

    case 'deleteLogFile':
        handleDeleteLogFile($input);
        break;

    case 'uploadIcon':
        handleUploadIcon();
        break;

    default:
        apiResponse('error', '未知的API操作');
}

/**
 * 处理管理员登录
 */
function handleLogin($input)
{
    global $conf;

    $token = trim($input['token'] ?? '');

    if (empty($token)) {
        apiResponse('error', '请输入管理密钥');
    }

    if (isset($conf['token']) && password_verify($token, $conf['token'])) {
        $_SESSION['ADMINTOKEN'] = $conf['token'];
        $_SESSION['login_time'] = time();
        apiResponse('success', '登录成功', ['redirect' => 'dashboard.php']);
    } else {
        apiResponse('error', '密钥错误，请检查后重试');
    }
}

/**
 * 处理设置管理密钥
 */
function handleSetToken($input)
{
    global $conf, $Data, $configPath;

    $newToken = trim($input['token'] ?? '');
    $confirmToken = trim($input['confirm_token'] ?? '');

    if (empty($newToken)) {
        apiResponse('error', '密钥不能为空');
    }

    if ($newToken !== $confirmToken) {
        apiResponse('error', '两次输入的密钥不一致');
    }

    if (strlen($newToken) < 6) {
        apiResponse('error', '密钥长度至少6位');
    }

    // 检查是否已设置密钥
    if (!empty($conf['token'])) {
        apiResponse('error', '密钥已存在，请使用登录功能');
    }

    $conf['token'] = password_hash($newToken, PASSWORD_DEFAULT);

    if (saveConfig($configPath, $conf, $Data)) {
        apiResponse('success', '管理密钥设置成功，请登录');
    } else {
        apiResponse('error', '保存密钥失败，请检查文件权限');
    }
}

/**
 * 处理退出登录
 */
function handleLogout()
{
    session_destroy();
    apiResponse('success', '已安全退出', ['redirect' => 'index.php']);
}

/**
 * 处理更新网站配置
 */
function handleUpdateSiteConfig($input)
{
    global $conf, $Data, $configPath;

    $newTitle = trim($input['site_title'] ?? '');
    $newDocs = trim($input['site_docs'] ?? '');
    $newIcp = trim($input['site_icp'] ?? '');
    $newEmail = trim($input['site_email'] ?? '');
    $bgPcUrl = trim($input['bg_pc_url'] ?? '');
    $bgMobileUrl = trim($input['bg_mobile_url'] ?? '');
    $pcColumns = intval($input['pc_columns'] ?? 5);
    $mobileColumns = intval($input['mobile_columns'] ?? 2);
    $siteStartTime = trim($input['site_start_time'] ?? '');
    $newToken = trim($input['site_token'] ?? '');

    if (empty($newTitle)) {
        apiResponse('error', '网站标题不能为空');
    }

    // 验证PC端列数范围（3-8列）
    if ($pcColumns < 3 || $pcColumns > 8) {
        apiResponse('error', 'PC端展示列数必须在3-8列之间');
    }

    // 验证手机端列数范围（1-3列）
    if ($mobileColumns < 1 || $mobileColumns > 3) {
        apiResponse('error', '手机端展示列数必须在1-3列之间');
    }

    // 验证建站时间格式
    if (!empty($siteStartTime)) {
        $timestamp = strtotime($siteStartTime);
        if ($timestamp === false) {
            apiResponse('error', '建站时间格式不正确');
        }
        // 将datetime-local格式转换为标准格式
        $conf['site_start_time'] = date('Y-m-d H:i:s', $timestamp);
    }

    $conf['title'] = htmlspecialchars($newTitle);
    $conf['docs'] = htmlspecialchars($newDocs);
    $conf['icp'] = htmlspecialchars($newIcp);
    $conf['email'] = htmlspecialchars($newEmail);

    // 保存背景地址，如果为空则使用默认值
    $conf['bg_pc_url'] = !empty($bgPcUrl) ? htmlspecialchars($bgPcUrl) : 'https://lh.ithxs.com/apis.php?act=pc';
    $conf['bg_mobile_url'] = !empty($bgMobileUrl) ? htmlspecialchars($bgMobileUrl) : 'https://lh.ithxs.com/apis.php?act=pe';

    // 保存背景地址，如果为空则使用默认值
    $conf['bg_pc_url'] = !empty($bgPcUrl) ? htmlspecialchars($bgPcUrl) : 'https://lh.ithxs.com/apis.php?act=pc';
    $conf['bg_mobile_url'] = !empty($bgMobileUrl) ? htmlspecialchars($bgMobileUrl) : 'https://lh.ithxs.com/apis.php?act=pe';

    // 保存列数配置
    $conf['pc_columns'] = $pcColumns;
    $conf['mobile_columns'] = $mobileColumns;

    $tokenChanged = false;
    if (!empty($newToken)) {
        if (strlen($newToken) < 6) {
            apiResponse('error', '新密钥长度至少6位');
        }
        $conf['token'] = password_hash($newToken, PASSWORD_DEFAULT);
        $tokenChanged = true;
    }

    if (saveConfig($configPath, $conf, $Data)) {
        $data = ['token_changed' => $tokenChanged];
        if ($tokenChanged) {
            // 如果密钥更改了，需要重新登录
            session_destroy();
            $data['redirect'] = 'index.php?message=' . urlencode('密钥已更新，请重新登录');
        }
        apiResponse('success', '网站配置更新成功', $data);
    } else {
        apiResponse('error', '保存配置失败，请检查文件权限');
    }
}

/**
 * 处理添加链接
 */
function handleAddLink($input)
{
    global $Data, $conf, $configPath;

    $title = trim($input['title'] ?? '');
    $url = trim($input['url'] ?? '');
    $description = trim($input['description'] ?? '');
    $icon = trim($input['icon'] ?? 'fas fa-link');

    if (empty($title)) {
        apiResponse('error', '链接标题不能为空');
    }

    if (empty($url)) {
        apiResponse('error', '链接地址不能为空');
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        apiResponse('error', '请输入有效的链接地址');
    }

    // 生成唯一ID
    $linkId = 'link_' . time() . '_' . uniqid();

    $newLink = [
        'id' => $linkId,
        'title' => htmlspecialchars($title),
        'description' => htmlspecialchars($description),
        'url' => filter_var($url, FILTER_SANITIZE_URL),
        'icon' => htmlspecialchars($icon),
        'clicks' => 0
    ];

    $Data[] = $newLink;

    if (saveConfig($configPath, $conf, $Data)) {
        $newIndex = count($Data) - 1;
        apiResponse('success', '链接添加成功', [
            'link' => $newLink,
            'index' => $newIndex
        ]);
    } else {
        apiResponse('error', '保存链接失败，请检查文件权限');
    }
}

/**
 * 处理更新链接
 */
function handleUpdateLink($input)
{
    global $Data, $conf, $configPath;

    $index = intval($input['index'] ?? -1);
    $title = trim($input['title'] ?? '');
    $url = trim($input['url'] ?? '');
    $description = trim($input['description'] ?? '');
    $icon = trim($input['icon'] ?? 'fas fa-link');

    if ($index < 0 || !isset($Data[$index])) {
        apiResponse('error', '链接索引无效');
    }

    if (empty($title)) {
        apiResponse('error', '链接标题不能为空');
    }

    if (empty($url)) {
        apiResponse('error', '链接地址不能为空');
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        apiResponse('error', '请输入有效的链接地址');
    }

    // 保留原有的点击数和ID
    $originalClicks = $Data[$index]['clicks'] ?? 0;
    $originalId = $Data[$index]['id'] ?? ('link_' . time() . '_' . uniqid());

    $Data[$index] = [
        'id' => $originalId,
        'title' => htmlspecialchars($title),
        'description' => htmlspecialchars($description),
        'url' => filter_var($url, FILTER_SANITIZE_URL),
        'icon' => htmlspecialchars($icon),
        'clicks' => $originalClicks
    ];

    if (saveConfig($configPath, $conf, $Data)) {
        apiResponse('success', '链接更新成功', [
            'link' => $Data[$index],
            'index' => $index
        ]);
    } else {
        apiResponse('error', '保存链接失败，请检查文件权限');
    }
}

/**
 * 处理删除链接
 */
function handleDeleteLink($input)
{
    global $Data, $conf, $configPath;

    $index = intval($input['index'] ?? -1);

    if ($index < 0 || !isset($Data[$index])) {
        apiResponse('error', '链接索引无效');
    }

    $deletedLink = $Data[$index];
    array_splice($Data, $index, 1);

    if (saveConfig($configPath, $conf, $Data)) {
        apiResponse('success', '链接删除成功', [
            'deleted_index' => $index,
            'deleted_link' => $deletedLink
        ]);
    } else {
        apiResponse('error', '删除链接失败，请检查文件权限');
    }
}

/**
 * 处理链接重新排序
 */
function handleReorderLinks($input)
{
    global $Data, $conf, $configPath;

    $newLinks = $input['links'] ?? [];

    if (!is_array($newLinks) || empty($newLinks)) {
        apiResponse('error', '链接数据无效');
    }

    // 验证新链接数据的完整性
    foreach ($newLinks as $link) {
        if (!isset($link['title']) || !isset($link['url'])) {
            apiResponse('error', '链接数据格式不正确');
        }
    }

    // 更新链接数据
    $Data = $newLinks;

    if (saveConfig($configPath, $conf, $Data)) {
        apiResponse('success', '链接排序已保存', [
            'total' => count($Data)
        ]);
    } else {
        apiResponse('error', '保存排序失败，请检查文件权限');
    }
}

/**
 * 获取链接列表
 */
function handleGetLinksList()
{
    global $Data;

    apiResponse('success', '获取链接列表成功', [
        'links' => $Data,
        'total' => count($Data)
    ]);
}

/**
 * 获取网站统计
 */
function handleGetSiteStats()
{
    global $Data, $conf;

    $totalClicks = 0;
    $totalLinks = count($Data);

    foreach ($Data as $link) {
        $totalClicks += intval($link['clicks'] ?? 0);
    }

    $stats = [
        'total_links' => $totalLinks,
        'total_clicks' => $totalClicks,
        'site_title' => $conf['title'] ?? '极简导航网',
        'site_description' => $conf['docs'] ?? '',
        'last_updated' => filemtime($configPath ?? '') ?: time()
    ];

    apiResponse('success', '获取统计信息成功', $stats);
}

/**
 * 获取访问记录数据库文件路径
 */
function getVisitDbPath($date = null)
{
    if ($date === null) {
        $date = date('Y-m-d');
    }
    $logsDir = dirname(__DIR__) . '/logs/visits';
    if (!is_dir($logsDir)) {
        mkdir($logsDir, 0755, true);
    }
    return $logsDir . '/visits_' . $date . '.json';
}

/**
 * 获取所有访问记录文件列表
 */
function getVisitFilesList()
{
    $fileList = [];
    $logsDir = dirname(__DIR__) . '/logs';

    // 检查新格式文件 (visits目录)
    $visitsDir = $logsDir . '/visits';
    if (is_dir($visitsDir)) {
        $files = glob($visitsDir . '/visits_*.json');
        foreach ($files as $file) {
            $filename = basename($file);
            if (preg_match('/visits_(\d{4}-\d{2}-\d{2})\.json/', $filename, $matches)) {
                $date = $matches[1];
                $fileList[] = [
                    'date' => $date,
                    'label' => date('Y年m月d日', strtotime($date)),
                    'filename' => $filename,
                    'path' => $file,
                    'size' => filesize($file),
                    'modified' => filemtime($file),
                    'type' => 'new'
                ];
            }
        }
    }

    // 检查旧格式文件 (直接在logs目录)
    $legacyFiles = glob($logsDir . '/visit_detail_*.json');
    foreach ($legacyFiles as $file) {
        $filename = basename($file);
        if (preg_match('/visit_detail_(\d{4}-\d{2}-\d{2})\.json/', $filename, $matches)) {
            $date = $matches[1];
            // 检查是否已经有新格式的文件，避免重复
            $exists = false;
            foreach ($fileList as $existing) {
                if ($existing['date'] === $date) {
                    $exists = true;
                    break;
                }
            }
            if (!$exists) {
                $fileList[] = [
                    'date' => $date,
                    'label' => date('Y年m月d日', strtotime($date)) . ' (旧格式)',
                    'filename' => $filename,
                    'path' => $file,
                    'size' => filesize($file),
                    'modified' => filemtime($file),
                    'type' => 'legacy'
                ];
            }
        }
    }

    // 按日期倒序排列
    usort($fileList, function ($a, $b) {
        return strcmp($b['date'], $a['date']);
    });

    return $fileList;
}

/**
 * 读取访问记录
 */
function readVisitRecords($date = null)
{
    $dbPath = getVisitDbPath($date);
    if (!file_exists($dbPath)) {
        // 如果新格式文件不存在，尝试读取旧格式文件
        return convertLegacyVisitDataForDate($date);
    }

    $content = file_get_contents($dbPath);
    return json_decode($content, true) ?: [];
}

/**
 * 读取多个日期的访问记录
 */
function readVisitRecordsMultiple($dates = null)
{
    if ($dates === null) {
        // 读取所有文件
        $filesList = getVisitFilesList();
        $allRecords = [];

        foreach ($filesList as $fileInfo) {
            $records = readVisitRecords($fileInfo['date']);
            $allRecords = array_merge($allRecords, $records);
        }

        return $allRecords;
    } else {
        // 读取指定日期的记录
        $allRecords = [];
        foreach ($dates as $date) {
            $records = readVisitRecords($date);
            $allRecords = array_merge($allRecords, $records);
        }

        return $allRecords;
    }
}

/**
 * 转换指定日期的旧格式访问数据
 */
function convertLegacyVisitDataForDate($date = null)
{
    if (!$date) {
        $date = date('Y-m-d');
    }

    $logsDir = dirname(__DIR__) . '/logs';
    $legacyFile = $logsDir . '/visit_detail_' . $date . '.json';

    if (!file_exists($legacyFile)) {
        return [];
    }

    $content = file_get_contents($legacyFile);
    $data = json_decode($content, true);

    if (!$data || !is_array($data)) {
        return [];
    }

    $records = [];
    foreach ($data as $item) {
        // 转换为新格式
        $record = [
            'id' => uniqid(),
            'ip_address' => $item['ip'] ?? '未知',
            'visit_time' => $item['timestamp'] ?? time(),
            'last_activity' => $item['timestamp'] ?? time(),
            'duration' => 0, // 旧数据没有停留时长
            'device_type' => parseDeviceType($item['user_agent'] ?? ''),
            'os' => parseOS($item['user_agent'] ?? ''),
            'browser' => parseBrowser($item['user_agent'] ?? ''),
            'user_agent' => $item['user_agent'] ?? '',
            'country' => '未知',
            'country_code' => '',
            'region' => '未知',
            'city' => '未知',
            'location' => '未知',
            'is_online' => false, // 旧数据默认为离线
            'referrer' => $item['referer'] ?? '',
            'page_url' => $item['request_uri'] ?? ''
        ];

        $records[] = $record;
    }

    return $records;
}

/**
 * 解析设备类型
 */
function parseDeviceType($userAgent)
{
    if (preg_match('/Mobile|Android|iPhone/', $userAgent)) {
        return 'Mobile';
    } elseif (preg_match('/Tablet|iPad/', $userAgent)) {
        return 'Tablet';
    } else {
        return 'Desktop';
    }
}

/**
 * 解析操作系统
 */
function parseOS($userAgent)
{
    if (preg_match('/Windows NT (\d+\.\d+)/', $userAgent, $matches)) {
        return 'Windows ' . $matches[1];
    } elseif (preg_match('/Mac OS X/', $userAgent)) {
        return 'macOS';
    } elseif (preg_match('/Linux/', $userAgent)) {
        return 'Linux';
    } elseif (preg_match('/Android/', $userAgent)) {
        return 'Android';
    } elseif (preg_match('/iPhone|iPad/', $userAgent)) {
        return 'iOS';
    } else {
        return '未知';
    }
}

/**
 * 解析浏览器
 */
function parseBrowser($userAgent)
{
    if (preg_match('/Firefox\/(\d+)/', $userAgent, $matches)) {
        return 'Firefox';
    } elseif (preg_match('/Chrome\/(\d+)/', $userAgent, $matches)) {
        return 'Chrome';
    } elseif (preg_match('/Safari\/(\d+)/', $userAgent, $matches) && !preg_match('/Chrome/', $userAgent)) {
        return 'Safari';
    } elseif (preg_match('/Edge\/(\d+)/', $userAgent, $matches)) {
        return 'Edge';
    } else {
        return '未知';
    }
}

/**
 * 保存访问记录
 */
function saveVisitRecords($records, $date = null)
{
    $dbPath = getVisitDbPath($date);
    return file_put_contents($dbPath, json_encode($records, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

/**
 * 获取用户IP地址
 */
function getUserIP()
{
    $ipKeys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];

    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }

    return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
}

/**
 * 获取用户设备信息
 */
function getUserDeviceInfo()
{
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

    // 检测设备类型
    $deviceType = 'Desktop';
    if (preg_match('/Mobile|Android|iPhone|iPad/', $userAgent)) {
        if (preg_match('/iPad/', $userAgent)) {
            $deviceType = 'Tablet';
        } else {
            $deviceType = 'Mobile';
        }
    }

    // 检测操作系统
    $os = 'Unknown';
    if (preg_match('/Windows NT (\d+\.\d+)/', $userAgent, $matches)) {
        $os = 'Windows ' . $matches[1];
    } elseif (preg_match('/Mac OS X (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'macOS ' . str_replace('_', '.', $matches[1]);
    } elseif (preg_match('/Linux/', $userAgent)) {
        $os = 'Linux';
    } elseif (preg_match('/Android (\d+\.\d+)/', $userAgent, $matches)) {
        $os = 'Android ' . $matches[1];
    } elseif (preg_match('/iPhone OS (\d+_\d+)/', $userAgent, $matches)) {
        $os = 'iOS ' . str_replace('_', '.', $matches[1]);
    }

    // 检测浏览器
    $browser = 'Unknown';
    if (preg_match('/Chrome\/(\d+)/', $userAgent, $matches)) {
        $browser = 'Chrome';
    } elseif (preg_match('/Firefox\/(\d+)/', $userAgent, $matches)) {
        $browser = 'Firefox';
    } elseif (preg_match('/Safari\/(\d+)/', $userAgent, $matches)) {
        if (!preg_match('/Chrome/', $userAgent)) {
            $browser = 'Safari';
        }
    } elseif (preg_match('/Edge\/(\d+)/', $userAgent, $matches)) {
        $browser = 'Edge';
    } elseif (preg_match('/Opera\/(\d+)/', $userAgent, $matches)) {
        $browser = 'Opera';
    }

    return [
        'device_type' => $deviceType,
        'os' => $os,
        'browser' => $browser,
        'user_agent' => $userAgent
    ];
}

/**
 * 获取IP地理位置信息
 */
function getLocationByIP($ip)
{
    // 这里可以集成第三方IP地理位置API
    // 为了演示，我们返回一个简单的示例
    if ($ip === '127.0.0.1' || $ip === '::1') {
        return [
            'country' => '本地',
            'country_code' => 'CN',
            'region' => '本地',
            'city' => '本地'
        ];
    }

    // 可以集成免费的IP地理位置API，如：
    // - ipapi.co
    // - ip-api.com
    // - ipinfo.io

    try {
        $url = "http://ip-api.com/json/{$ip}?lang=zh-CN";
        $context = stream_context_create([
            'http' => [
                'timeout' => 3,
                'user_agent' => 'DaoHang/1.0'
            ]
        ]);

        $response = @file_get_contents($url, false, $context);
        if ($response) {
            $data = json_decode($response, true);
            if ($data && $data['status'] === 'success') {
                return [
                    'country' => $data['country'] ?? '未知',
                    'country_code' => $data['countryCode'] ?? 'XX',
                    'region' => $data['regionName'] ?? '未知',
                    'city' => $data['city'] ?? '未知'
                ];
            }
        }
    } catch (Exception $e) {
        // 忽略错误，返回默认值
    }

    return [
        'country' => '未知',
        'country_code' => 'XX',
        'region' => '未知',
        'city' => '未知'
    ];
}

/**
 * 处理获取访问记录
 */
/**
 * 处理获取访问文件列表
 */
function handleGetVisitFiles()
{
    $filesList = getVisitFilesList();

    // 格式化文件信息
    $formattedFiles = array_map(function ($file) {
        return [
            'date' => $file['date'],
            'label' => $file['date'] . ' (' . formatFileSize($file['size']) . ')',
            'filename' => $file['filename'],
            'size' => $file['size'],
            'modified' => date('Y-m-d H:i:s', $file['modified'])
        ];
    }, $filesList);

    apiResponse('success', '获取访问文件列表成功', [
        'files' => $formattedFiles,
        'total' => count($formattedFiles)
    ]);
}

/**
 * 格式化文件大小
 */
function formatFileSize($bytes)
{
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return round($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' B';
    }
}

function handleGetVisitRecords($input)
{
    $selectedFile = $input['selected_file'] ?? null;
    $ipSearch = trim($input['ip_search'] ?? '');
    $page = max(1, intval($input['page'] ?? 1));
    $pageSize = max(1, min(100, intval($input['page_size'] ?? 10)));

    // 根据选择的文件读取记录
    if ($selectedFile && $selectedFile !== 'all') {
        $records = readVisitRecords($selectedFile);
    } else {
        // 读取所有记录
        $records = readVisitRecordsMultiple();
    }

    // 筛选记录（只保留IP搜索）
    $filteredRecords = array_filter($records, function ($record) use ($ipSearch) {
        // IP搜索
        if (!empty($ipSearch) && strpos($record['ip_address'], $ipSearch) === false) {
            return false;
        }

        return true;
    });

    // 按访问时间倒序排列
    usort($filteredRecords, function ($a, $b) {
        return $b['visit_time'] - $a['visit_time'];
    });

    // 分页
    $totalRecords = count($filteredRecords);
    $totalPages = ceil($totalRecords / $pageSize);
    $offset = ($page - 1) * $pageSize;
    $pagedRecords = array_slice($filteredRecords, $offset, $pageSize);

    // 计算统计信息
    $todayStart = strtotime('today');
    $todayRecords = array_filter($records, function ($record) use ($todayStart) {
        return $record['visit_time'] >= $todayStart;
    });

    $todayVisits = count($todayRecords);
    $todayVisitors = count(array_unique(array_column($todayRecords, 'ip_address')));

    // 计算平均停留时长
    $totalDuration = array_sum(array_column($todayRecords, 'duration'));
    $avgDuration = $todayVisits > 0 ? round($totalDuration / $todayVisits) : 0;

    // 计算在线访客数（最近5分钟有活动的）
    $onlineThreshold = time() - 300; // 5分钟
    $onlineVisitors = count(array_filter($records, function ($record) use ($onlineThreshold) {
        return ($record['last_activity'] ?? $record['visit_time']) > $onlineThreshold;
    }));

    $stats = [
        'today_visits' => $todayVisits,
        'today_visitors' => $todayVisitors,
        'avg_duration' => $avgDuration,
        'online_visitors' => $onlineVisitors
    ];

    apiResponse('success', '获取访问记录成功', [
        'records' => $pagedRecords,
        'total_records' => $totalRecords,
        'total_pages' => $totalPages,
        'current_page' => $page,
        'page_size' => $pageSize,
        'stats' => $stats
    ]);
}

/**
 * 处理获取在线访客数
 */
function handleGetOnlineVisitors()
{
    $records = readVisitRecords();

    // 计算在线访客数（最近5分钟有活动的）
    $onlineThreshold = time() - 300; // 5分钟
    $onlineVisitors = count(array_filter($records, function ($record) use ($onlineThreshold) {
        return ($record['last_activity'] ?? $record['visit_time']) > $onlineThreshold;
    }));

    apiResponse('success', '获取在线访客数成功', ['count' => $onlineVisitors]);
}

/**
 * 处理导出访问记录
 */
function handleExportVisitRecords($input)
{
    $timeFilter = $input['time_filter'] ?? 'today';
    $ipSearch = trim($input['ip_search'] ?? '');

    $records = readVisitRecords();

    // 时间筛选逻辑（与获取记录相同）
    $now = time();
    $startTime = 0;

    switch ($timeFilter) {
        case 'today':
            $startTime = strtotime('today');
            break;
        case 'yesterday':
            $startTime = strtotime('yesterday');
            $endTime = strtotime('today') - 1;
            break;
        case 'week':
            $startTime = strtotime('-7 days');
            break;
        case 'month':
            $startTime = strtotime('-30 days');
            break;
    }

    // 筛选记录
    $filteredRecords = array_filter($records, function ($record) use ($startTime, $endTime, $ipSearch) {
        if (isset($endTime) && $record['visit_time'] > $endTime) {
            return false;
        }
        if ($record['visit_time'] < $startTime) {
            return false;
        }
        if (!empty($ipSearch) && strpos($record['ip_address'], $ipSearch) === false) {
            return false;
        }
        return true;
    });

    // 生成CSV
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="visit_records_' . date('Y-m-d_H-i-s') . '.csv"');

    $output = fopen('php://output', 'w');

    // 添加BOM以支持中文
    fwrite($output, "\xEF\xBB\xBF");

    // CSV头部
    fputcsv($output, ['访问时间', 'IP地址', '地理位置', '停留时长(秒)', '设备类型', '操作系统', '浏览器', '状态']);

    // CSV数据
    foreach ($filteredRecords as $record) {
        $location = ($record['country'] ?? '未知') . ' ' . ($record['region'] ?? '') . ' ' . ($record['city'] ?? '');
        $status = ($record['is_online'] ?? false) ? '在线' : '离线';

        fputcsv($output, [
            date('Y-m-d H:i:s', $record['visit_time']),
            $record['ip_address'],
            trim($location),
            $record['duration'] ?? 0,
            $record['device_type'] ?? '未知',
            $record['os'] ?? '未知',
            $record['browser'] ?? '未知',
            $status
        ]);
    }

    fclose($output);
    exit;
}

/**
 * 处理记录访问
 */
function handleRecordVisit($input)
{
    $ip = getUserIP();
    $deviceInfo = getUserDeviceInfo();
    $locationInfo = getLocationByIP($ip);

    $visitRecord = [
        'id' => uniqid(),
        'ip_address' => $ip,
        'visit_time' => time(),
        'device_type' => $deviceInfo['device_type'],
        'os' => $deviceInfo['os'],
        'browser' => $deviceInfo['browser'],
        'user_agent' => $deviceInfo['user_agent'],
        'country' => $locationInfo['country'],
        'country_code' => $locationInfo['country_code'],
        'region' => $locationInfo['region'],
        'city' => $locationInfo['city'],
        'location' => $locationInfo['country'] . ' ' . $locationInfo['region'] . ' ' . $locationInfo['city'],
        'referrer' => $_SERVER['HTTP_REFERER'] ?? '',
        'page_url' => $input['page_url'] ?? ''
    ];

    // 按当前日期保存记录
    $today = date('Y-m-d');
    $records = readVisitRecords($today);
    $records[] = $visitRecord;

    // 保持每日最多1000条记录
    if (count($records) > 1000) {
        $records = array_slice($records, -1000);
    }

    saveVisitRecords($records, $today);

    apiResponse('success', '访问记录已保存', ['visit_id' => $visitRecord['id']]);
}

/**
 * 处理更新访问时长 - 已禁用，不再跟踪停留时间
 */
/*
function handleUpdateVisitDuration($input)
{
    $visitId = $input['visit_id'] ?? '';
    $duration = max(0, intval($input['duration'] ?? 0));
    $isFinalUpdate = $input['is_final'] ?? false; // 是否为最终上报（页面离开时）

    if (empty($visitId)) {
        apiResponse('error', '访问ID不能为空');
    }

    // 先尝试今天的记录
    $today = date('Y-m-d');
    $records = readVisitRecords($today);
    $updated = false;
    $targetDate = $today;

    foreach ($records as &$record) {
        if ($record['id'] === $visitId) {
            $record['duration'] = $duration;
            $record['last_activity'] = time();
            
            // 只有在最终上报时才标记为离线
            if ($isFinalUpdate) {
                $record['is_online'] = false;
            }
            
            $updated = true;
            break;
        }
    }
    
    // 如果今天的记录中没找到，尝试昨天的记录（处理跨日访问）
    if (!$updated) {
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $records = readVisitRecords($yesterday);
        
        foreach ($records as &$record) {
            if ($record['id'] === $visitId) {
                $record['duration'] = $duration;
                $record['last_activity'] = time();
                
                if ($isFinalUpdate) {
                    $record['is_online'] = false;
                }
                
                $updated = true;
                $targetDate = $yesterday;
                break;
            }
        }
    }

    if ($updated) {
        saveVisitRecords($records, $targetDate);
        apiResponse('success', '访问时长已更新');
    } else {
        apiResponse('error', '访问记录未找到');
    }
}
*/

/**
 * 处理删除日志文件
 */
function handleDeleteLogFile($input)
{
    $filename = trim($input['filename'] ?? '');

    if (empty($filename)) {
        apiResponse('error', '文件名不能为空');
    }

    // 安全检查：只允许删除.json文件，且文件名不能包含路径分隔符
    if (
        pathinfo($filename, PATHINFO_EXTENSION) !== 'json' ||
        strpos($filename, '/') !== false ||
        strpos($filename, '\\') !== false ||
        strpos($filename, '..') !== false
    ) {
        apiResponse('error', '无效的文件名');
    }

    $logsDir = dirname(__DIR__) . '/logs';
    $filePath = $logsDir . '/' . $filename;

    if (!file_exists($filePath)) {
        apiResponse('error', '文件不存在');
    }

    if (unlink($filePath)) {
        apiResponse('success', '日志文件删除成功');
    } else {
        apiResponse('error', '删除文件失败，请检查文件权限');
    }
}

/**
 * 处理图标上传
 */
function handleUploadIcon()
{
    // 检查是否有文件上传
    if (!isset($_FILES['icon']) || $_FILES['icon']['error'] !== UPLOAD_ERR_OK) {
        $errorMsg = '上传失败';
        if (isset($_FILES['icon'])) {
            switch ($_FILES['icon']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $errorMsg = '文件大小超出限制';
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $errorMsg = '没有文件被上传';
                    break;
                default:
                    $errorMsg = '上传失败，错误代码：' . $_FILES['icon']['error'];
            }
        }
        apiResponse('error', $errorMsg);
    }

    $file = $_FILES['icon'];

    // 验证文件类型
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml', 'image/x-icon'];
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico'];

    $fileType = strtolower($file['type']);
    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($fileType, $allowedTypes) && !in_array($fileExtension, $allowedExtensions)) {
        apiResponse('error', '不支持的文件类型，仅支持 JPG、PNG、GIF、WEBP、SVG、ICO 格式');
    }

    // 验证文件大小（限制为2MB）
    $maxSize = 2 * 1024 * 1024; // 2MB
    if ($file['size'] > $maxSize) {
        apiResponse('error', '文件大小不能超过 2MB');
    }

    // 创建上传目录
    $uploadDir = dirname(__DIR__) . '/uploads/img';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            apiResponse('error', '无法创建上传目录，请检查权限');
        }
    }

    // 生成唯一文件名
    $newFileName = 'icon_' . time() . '_' . uniqid() . '.' . $fileExtension;
    $uploadPath = $uploadDir . '/' . $newFileName;

    // 移动上传文件
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        // 返回相对于网站根目录的路径（从 admin 目录访问需要 ../）
        $relativePath = '/uploads/img/' . $newFileName;
        apiResponse('success', '图标上传成功', [
            'url' => $relativePath,
            'filename' => $newFileName
        ]);
    } else {
        apiResponse('error', '文件上传失败，请检查目录权限');
    }
}
